import axios from 'axios' //axios
import router from '../router' //路由

const instance = axios.create({
    baseURL: "http://localhost:80", //指定请求的公共部分
    timeout: 3000, //超时时间
    withCredentials: true //允许携带cookie
});

//为axios指定请求的拦截器
instance.interceptors.request.use(config => {
    //针对登录的请求，直接放行
    let excludePath = ['/login'];//排除的路径
    let url = config.url;
    url = url.substring(0, url.indexOf("/", '/login'.length));
    if (excludePath.includes(url)) {//不携带token
        return config;//放行这次请求
    }
    //获取本地token
    let token = window.localStorage.getItem("token");
    if (token) {
        config.headers['Authorization'] = token;//将token设置到Authorization请求头中
    }
    console.log("----请求拦截器----");
    console.log("token:" + token)
    return config;//放行这次请求
});
//为axios指定响应的拦截器
instance.interceptors.response.use(config => {
    let status = config.data.code;
    let token = window.localStorage.getItem("token");
    if(token == null){
        router.currentRoute.path !== '/login' && router.push("/login");
    }
    console.log(status)//获取服务端响应的状态
    if (status == 401) {//权限不足
        //重定向到登录
        //移除本地的token
        localStorage.removeItem("token");
        //跳转到login路由
        router.currentRoute.path !== '/login' && router.push("/login");
    }
    return config;//放行这次响应
});

//导出，公开
export default instance
